// Package rpc
// Author liuzhiyong
// Date 2023/11/21
// Description 初始化其他服务的RPC客户端
package rpc

import (
	"errors"
	"fmt"
	"gitee.com/liu_zy_developer/go_order_service/config"
	"gitee.com/liu_zy_developer/go_order_service/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

var (
	GoodsCli proto.GoodsClient // 商品服务
	StockCli proto.StockClient // 库存服务
)

// InitSrvClient 初始化rpc客户端
func InitSrvClient() error {
	// 校验远程调用的服务名是否配置
	if len(config.Conf.GoodsService.Name) == 0 {
		return errors.New("invalid GoodsService.Name")
	}
	if len(config.Conf.StockService.Name) == 0 {
		return errors.New("invalid StockService.Name")
	}

	// consul 实现服务发现

	// 创建商品客户端: 程序启动的时候请求Consul, 获取商品服务可用的服务列表
	goodsConn, err := grpc.Dial(fmt.Sprintf("consul://%s/%s?wait=14s", config.Conf.ConsulConfig.Addr, config.Conf.GoodsService.Name),
		// 指定round_robin策略
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		fmt.Printf("dial goods_srv failed, err:%v\n", err)
		return err
	}
	GoodsCli = proto.NewGoodsClient(goodsConn)

	// 创建库存服务客户端
	stockConn, err := grpc.Dial(
		// consul服务
		fmt.Sprintf("consul://%s/%s?wait=14s", config.Conf.ConsulConfig.Addr, config.Conf.StockService.Name),
		// 指定round_robin策略
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		fmt.Printf("dial stock_srv failed, err:%v\n", err)
		return err
	}
	StockCli = proto.NewStockClient(stockConn)
	return nil
}
